//
//  SurroundViewController.m
//  
//
//  Created by 郭明皓 on 15/10/24.
//
//

#import "SurroundViewController.h"
#import "GMHSurroundModel.h"
#import "TuijianCell.h"

#import "GMHFindDetailViewController.h"
#import "GMHDataFiled.h"
#import <UIImageView+WebCache.h>
#import <MJRefresh.h>
#import <AFNetworking.h>
#import "SearchController.h"
#import <Reachability.h>
#import "MBProgressHUD.h"
#import "DKNightVersion.h"
@interface SurroundViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>
@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, assign)int pageIndex;
@property (nonatomic, assign)BOOL isUpPull;
@property (nonatomic, retain)NSMutableArray *surroundArr;
@property (nonatomic, retain)UISearchBar *search;
@property (nonatomic, assign)NSInteger flag;
@property (nonatomic, retain)NSDictionary *endDic;

@end

@implementation SurroundViewController
- (void)dealloc
{
    [_endDic release];
    [_search release];
    [_surroundArr release];
    [_tableView release];
    [super dealloc];
}
- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
    if ([self isConnectionAvailable]) {
        [self viewDidLoad];
    }
    else
    {
        //1.找沙盒路径
        NSString *sandboxpath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        //2.拼接电影的文件夹
        NSString *movieFile = [sandboxpath stringByAppendingPathComponent:@"Travel"];
        //3.创建一个文件管理者
        NSFileManager *manager = [NSFileManager defaultManager];
        //通过管理者调用方法,根据路径判断文件夹是否存在
        if (![manager fileExistsAtPath:movieFile]) {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];//<span style="font-family: Arial, Helvetica, sans-serif;">MBProgressHUD为第三方库，不需要可以省略或使用AlertView</span>
            hud.removeFromSuperViewOnHide =YES;
            hud.mode = MBProgressHUDModeText;
            hud.labelText = @"当前网络不可用，请检查网络连接";  //提示的内容
            hud.minSize = CGSizeMake(132.f, 58.0f);
            [hud hide:YES afterDelay:3];
        }
        else
        {
            
            NSLog(@"没有网络时");
            NSString *sendBoxPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
            NSString *CachesPath = [sendBoxPath stringByAppendingPathComponent:@"Travel/Surround/Title.plist"];
            NSDictionary *surroundDic = [NSKeyedUnarchiver unarchiveObjectWithFile:CachesPath];
            self.surroundArr = [GMHSurroundModel baseModelArry:surroundDic[@"data"][@"items"]];
            
        }
    }

}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    self.navigationItem.backBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil] autorelease];
    self.navigationController.navigationBar.nightBarTintColor = UIColorFromRGB(0x444444);
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [self.tableView release];
    self.tableView.nightBackgroundColor = UIColorFromRGB(0x343434);
    self.tableView.nightSeparatorColor = UIColorFromRGB(0x313131);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 100;
    self.tableView.nightBackgroundColor = [UIColor blackColor];
    self.tableView.nightSeparatorColor = [UIColor darkGrayColor];
    
        [self.tableView reloadData];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(click)];

    
    self.surroundArr = [NSMutableArray array];
    [self DownPull];
    [self UpPull];

    
}
- (void)click
{
    SearchController *city = [[SearchController alloc]init];
    [self.navigationController pushViewController:city animated:YES];
    [city release];

}

#pragma mark 刷新加载
- (void)UpPull
{
    __block SurroundViewController *find = self;
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self.tableView.footer endRefreshing];
        self.pageIndex++;
        self.isUpPull = YES;
        [find create];
    }];
}
- (void)DownPull
{
    __block SurroundViewController *find = self;
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.pageIndex = 1;
        self.isUpPull = NO;
        [find create];
    }];
    [self.tableView.header beginRefreshing];
}

#pragma mark 加载数据
- (void)create
{
    [GMHDataFiled isHaveFileDocument];
    [GMHDataFiled isHaveFileSurround];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *strurl = [NSString stringWithFormat:@"http://appapi.yaochufa.com/v2/Product/GetAroundProductList?system=android&machineCode=ffffffff-9317-02f2-ffff-fffff60c2478&province=1&pageIndex=%d&city=%%E5%%A4%%A7%%E8%%BF%%9E&latitude=38.883328&channel=xiaomimarket&pageSize=20&sort=n&version=4.3.1&longitude=121.54408", _pageIndex];

    if (self.isUpPull == NO) {
        [self.surroundArr removeAllObjects];
    }
    [manager GET:strurl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        
        NSMutableArray *arry = [GMHSurroundModel baseModelArry:dic[@"data"][@"items"]];
        
        [self.surroundArr addObjectsFromArray:arry];
        if (self.flag == self.surroundArr.count) {
            [self.tableView.footer endRefreshing];
            [self.tableView reloadData];
        }
        self.flag = self.surroundArr.count;
        if (_surroundArr.count > 0) {
            [self.tableView.header endRefreshing];
            [self.tableView.footer endRefreshing];
            [self.tableView reloadData];
        }
       
        NSString *sendBoxPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
        NSString *CachesPath = [sendBoxPath stringByAppendingPathComponent:@"Travel/Surround/Title.plist"];
        [NSKeyedArchiver archiveRootObject:dic toFile:CachesPath];



    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"周边加载失败");
    }];
}


#pragma mark tableview协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.surroundArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *strs = @"SurroundtableView";
    TuijianCell *cell = [tableView dequeueReusableCellWithIdentifier:strs];
    if (!cell) {
        cell = [[TuijianCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strs];
    }
    if (self.surroundArr.count != 0) {
        GMHSurroundModel *sur = self.surroundArr[indexPath.row];
        [cell.leftimageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://cdn5.jinxidao.com/%@", sur.mImageUrl]]placeholderImage:[UIImage imageNamed:@"travel.jpg"]];
        cell.title.text = sur.productName;
        cell.describe.text = [NSString stringWithFormat:@"[%@]%@", sur.cityName, sur.productTitleContent];
        cell.money.text = [NSString stringWithFormat:@"￥%@", sur.price];
        cell.normalMoney.text = [NSString stringWithFormat:@"￥%@", sur.retailPrice];
        cell.sell.text = [NSString stringWithFormat:@"已售%@", sur.saledCount];
        // 字体删除线
        NSMutableAttributedString *content = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"￥%@", sur.retailPrice]];
        NSRange contentRange = {0.9,[content length]};
        [content addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleThick] range:contentRange];
        cell.normalMoney.attributedText = content;

    }
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    self.tabBarController.tabBar.hidden = YES;
    GMHFindDetailViewController *detail = [[GMHFindDetailViewController alloc]init];
    [self.navigationController pushViewController:detail animated:YES];
    [detail release];
    GMHSurroundModel *find = self.surroundArr[indexPath.row];
    detail.productIds = find.productId;
    detail.model = find;
}
//判断是否有网络
-(BOOL) isConnectionAvailable{
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = NO;
            //NSLog(@"notReachable");
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = YES;
            //NSLog(@"WIFI");
            break;
        case ReachableViaWWAN:
            isExistenceNetwork = YES;
            //NSLog(@"3G");
            break;
    }
    
    if (!isExistenceNetwork) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];//<span style="font-family: Arial, Helvetica, sans-serif;">MBProgressHUD为第三方库，不需要可以省略或使用AlertView</span>
        hud.removeFromSuperViewOnHide =YES;
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"当前网络不可用，请检查网络连接";  //提示的内容
        hud.minSize = CGSizeMake(132.f, 58.0f);
        [hud hide:YES afterDelay:1];
        return NO;
    }
    
    return isExistenceNetwork;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
